using System;
using System.Net;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using System.Diagnostics;
using Project.Admin.Models;
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

namespace Project.Admin.Controllers
{
    public class AdminController : Controller
    {
        private readonly ILogger<AdminController> _logger;
        public AdminController(ILogger<AdminController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public IActionResult Login(string ReturnUrl)
        {
            if (HttpContext.User.FindFirstValue("AccountEval") != null)
            {
                string loginName = HttpContext.User.FindFirstValue("AccountEval").ToString();
                ViewData["AccountEval"] = WebUtility.UrlDecode(loginName);
            }
            if (HttpContext.User.FindFirstValue("PassWordEval") != null)
            {
                string unitName = HttpContext.User.FindFirstValue("PassWordEval").ToString();
                ViewData["PassWordEval"] = WebUtility.UrlDecode(unitName);
            }
            if (ReturnUrl != null && ReturnUrl != "")
            {
                ViewData["ReturnUrl"] = ReturnUrl;
            }
            return View();
        }

        /// <summary>
        /// 下拉列表
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public string GetUnitCode()
        {
            DataTable dt = new DataTable("Table");
            string[] colname = new string[4] { "Id", "PId", "Name", "UnitClass" };
            for (int i = 0; i < colname.Length; i++)
            {
                DataColumn dc = new DataColumn(colname[i], typeof(String));
                dt.Columns.Add(dc);
            }
            for (int i = 0; i < 10; i++)
            {
                DataRow dr = dt.NewRow();
                if (i == 0)
                {
                    dr["Id"] = "1000";
                    dr["PId"] = "";
                    dr["Name"] = "全国";
                    dr["UnitClass"] = "1";
                }
                else
                {
                    dr["Id"] = "100" + i;
                    dr["PId"] = "1000";
                    dr["Name"] = "全省" + i;
                    dr["UnitClass"] = "2";
                }
                dt.Rows.Add(dr);
            }
            return JsonConvert.SerializeObject(dt);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public string Login(LoginDto Dto)
        {
            if (Dto.Account == "admin" && Dto.Password == "admin")
            {
                _logger.LogWarning("用户：" + Dto.Account + "登录");
                CreateCookie(Dto.Account, Dto.Password);
                return JsonConvert.SerializeObject(new { state = "OK", mc = "登录成功", url = "/Home/Index" });
            }
            else
            {
                CreateCookie(Dto.Account, null);
                return JsonConvert.SerializeObject(new { state = "fail", mc = "用户名或密码不对", url = "/Admin/Login" });
            }
        }

        /// <summary>
        /// Cookie验证
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public void CreateCookie(string account, string password)
        {
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            var claims = new List<Claim>();
            if (account != null && account != ""!)
            {
                claims.Add(new Claim("AccountEval", WebUtility.UrlEncode(account)));
            }
            if (password != null && password != "")
            {
                claims.Add(new Claim("PassWordEval", WebUtility.UrlEncode(password)));
            }
            var claimsidentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var authproperties = new AuthenticationProperties
            {
                AllowRefresh = true,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(30),
                IsPersistent = true
            };
            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsidentity), authproperties).Wait();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
